
import *  as turf from '@turf/turf'
import { apiList } from '@/api/apiList'
import {v1} from 'uuid'
import iconList from '@/common/IconList'
import { default as proj4 } from "proj4"
import _ from 'lodash'


// 目标识别和变化监测的shp渲染（需要根据分类区分）
// name_arr = ['QMC','BHLX']
const loadShp = (item, distance = 25000, name_arr = [], color_type = 'BHLX') => {

  let color_arr = {}
  
  return new Promise((resolve) => {
    apiList.getShpInfo({ filePath: item }).then(res => {
      let resjson = res.result
      if (_.has(res.result, 'crs') && res.result.crs.properties.name == null) {
        let crsname = 'wkt' + _.random(0, 999999)
        proj4.defs(crsname, resjson.wkt);
        Cesium.GeoJsonDataSource.crsNames[crsname] = function (coordinates) {
          return Cesium.Cartesian3.fromDegrees(...proj4(crsname, 'EPSG:4326', coordinates), 0)
        }
        res.result.crs.properties.name = crsname
      }

      if (res.result?.crs?.properties?.name == 'CRS:84') {
        delete res.result['crs']
      }

      Cesium.GeoJsonDataSource.load(res.result, {
        stroke: Cesium.Color.HOTPINK,
        fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.0),
        strokeWidth: 3
      }).then(ds => {
        

        ds.entities.values.map(e => {

          // console.log(e.properties[color_type]);
          _.has(color_arr, e.properties[color_type]) ? "" : color_arr[e.properties[color_type]] = Cesium.Color.fromRandom({alpha: 1.0});
        // console.log(e.properties[color_type]);

          //添加label
          let name = name_arr.map(item => {
            return e.properties[item]
          })
          let resname = name.join('-')
          e.position = e.polygon.hierarchy._value.positions[0]
          e.label = {
            text: resname == '-' ? '消失' : resname,
            // text: '消失',
            // text: name.join('-'),
            scaleByDistance: new Cesium.NearFarScalar(100, 1.0, distance, 0.0),
            showBackground: true,
            backgroundColor: color_arr[e.properties[color_type]],
            // backgroundColor: Cesium.Color.fromCssColorString("#6C90FE"),
          }

          e.polyline = {
            show: true, //是否显示，默认显示
            positions: e.polygon.hierarchy._value.positions,
            width: 2, //线的宽度（像素），默认为1
            // granularity: Cesium.Math.RADIANS_PER_DEGREE,
            material: color_arr[e.properties[color_type]], //线的颜色，默认为白色
          }

          // 修改polygon 颜色
          console.log(e.polygon);
          e.polygon.outlineColor = color_arr[e.properties[color_type]]
          // e.polygon.material = color_arr[e.properties[color_type]]
        })

        resolve(ds)
      })
    })
    
  })

}

const getFinalPos = (pos, spatial_ref) => {
  const epsg32651 = spatial_ref
  const epsg4326 = '+proj=longlat +datum=WGS84 +no_defs +type=crs';
  proj4.defs('EPSG:32651', epsg32651);
  proj4.defs('EPSG:4326', epsg4326);
  return proj4('EPSG:32651', 'EPSG:4326', pos)
}

const loadGeojson = function (data) {
  // 点位 区域 label
  var imgaes = `/assets/v2/dw_search_on.png`
  let entities_arr = []

  data.features.map(item => {
    // 点位
    if (item.geometry.type == 'Point') {
      entities_arr.push(new Cesium.Entity({
        description: '椭圆', //描述
        position: Cesium.Cartesian3.fromDegrees(item.geometry.coordinates[0], item.geometry.coordinates[1], 0),
        show: true,
        label: {
          //文字标签
          text: item.properties.name,
          font: '500 30px Helvetica', // 15pt monospace
          scale: 0.5,
          style: Cesium.LabelStyle.FILL,
          fillColor: Cesium.Color.WHITE,
          pixelOffset: new Cesium.Cartesian2(0, -60), //偏移量
          showBackground: true,
          backgroundColor: new Cesium.Color(0.5, 0.6, 1, 1.0),
          // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
        },
        billboard: {
          //图标
          image: imgaes,
          width: 25,
          pixelOffset: new Cesium.Cartesian2(0, -25), //偏移量
          height: 50,
          // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
        },
      }))
    }else if(item.geometry.type == 'Polygon'){
      // new Cesium.PolygonHierarchy(_self.positions)
      // Cesium.Cartesian3.fromDegreesArray(item1.flat(Infinity))
      // 
      var polygon = turf.polygon(item.geometry.coordinates);
      var centroid = turf.centroid(polygon);
      console.log(centroid);

      let positions = Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates.flat(Infinity))

      entities_arr.push(new Cesium.Entity({
        description: '椭圆', //描述
        position: Cesium.Cartesian3.fromDegrees(centroid.geometry.coordinates[0], centroid.geometry.coordinates[1], 0),
        show: true,
        label: {
          //文字标签
          text: item.properties.name,
          font: '500 30px Helvetica', // 15pt monospace
          scale: 0.5,
          style: Cesium.LabelStyle.FILL,
          fillColor: Cesium.Color.WHITE,
          pixelOffset: new Cesium.Cartesian2(0, -10), //偏移量
          showBackground: true,
          backgroundColor: new Cesium.Color(0.5, 0.6, 1, 1.0),
          // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
        },
        polygon: {
          show: true,
          hierarchy: new Cesium.PolygonHierarchy(positions),
          // height: 0,
          material: Cesium.Color.CYAN.withAlpha(0.5),
          outline: true,
          outlineColor: Cesium.Color.BLACK,
          // classificationType: Cesium.ClassificationType.BOTH
        },
        polyline: {
          positions: positions,
          width: 3,
          material: Cesium.Color.BLUE.withAlpha(0.5),
          // clampToGround: true,
        },
        
      }))
    }
  })
  return entities_arr
}

function drawAndShareImage(bgsrc, src, fun) {
  
  console.log(_.has(window, bgsrc + src));
  if (_.has(window, bgsrc + src)) {
    console.log(bgsrc + src);
    if (fun) fun(window[bgsrc + src])
  }else{
    let canvas = document.createElement("canvas");
    canvas.width = 92;
    canvas.height = 230;
    let context = canvas.getContext("2d");
    context.rect(0, 0, canvas.width, canvas.height);
    let bgImg = new Image();
    bgImg.src = bgsrc; // 背景图的url
    bgImg.crossOrigin = "Anonymous";
    bgImg.onload = () => {
      context.drawImage(bgImg, 0, 0, 92, 230);
      let img = new Image();
      img.src = src; // 需要合进去的图片url
      img.crossOrigin = "Anonymous";
      img.onload = () => {
        context.drawImage(img, 16, 16, 60, 60);
        let base64 = canvas.toDataURL("image/png");
        window[bgsrc + src] = base64
        if (fun) fun(base64);
      };
    };

  }
}

// 根据符号库生成entity
const loadPointIcon = function (item,bgimg = 'linePoi.png') {
  item.icon = item.icon || iconList.Crosshair
  // linePoi.png
  return new Promise((resolve) => {
    drawAndShareImage(`/assets/3d/t/${bgimg}`,item.icon,function (params) {
      let e = loadPointNew(item.loc,item.name,params)
      resolve(e)
    })
    
  })
  
}

const loadPointNew = function (pos, text,imgaes) {
  // var imgaes = `/assets/v2/icon_bh.png`
  // var imgaes = `/assets/3d/t/${imgUrl}.png`
  let entity = new Cesium.Entity({
    description: '椭圆', //描述
    id: v1(),
    position: Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 0),
    show: true,
    label: {
      //文字标签
      text: text,
      font: '500 30px Helvetica', // 15pt monospace
      scale: 0.5,
      style: Cesium.LabelStyle.FILL,
      fillColor: Cesium.Color.WHITE,
      pixelOffset: new Cesium.Cartesian2(0, -30), //偏移量
      showBackground: true,
      backgroundColor: new Cesium.Color(0.5, 0.6, 1, 1.0),
      // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
    },
    // polyline: {
    //   positions: [
    //     Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 80),
    //     Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 100),
    //   ],
    //   width: new Cesium.ConstantProperty(5),
    //   // material : Cesium.Color.fromRandom({alpha : 1.0}),
    //   material: new Cesium.PolylineGlowMaterialProperty({
    //     glowPower: 3,
    //     color: Cesium.Color.fromRandom({ alpha: 1.0 }),
    //   }),
    //   // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 100000, 0.0)
    // },
    billboard: {
      //图标
      image: imgaes,
      width: 46,
      // pixelOffset: new Cesium.Cartesian2(0, -50), //偏移量
      pixelOffset: new Cesium.Cartesian2(0, -57), //偏移量
      height: 115,
      // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
    },
  })

  return entity
}
const loadPoint = function (pos, text, imgUrl = 'linePoi') {
  var imgaes = `/assets/v2/icon_bh.png`
  // var imgaes = `/assets/3d/t/${imgUrl}.png`
  let entity = new Cesium.Entity({
    description: '椭圆', //描述
    id: v1(),
    position: Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 0),
    show: true,
    label: {
      //文字标签
      text: text,
      font: '500 30px Helvetica', // 15pt monospace
      scale: 0.5,
      style: Cesium.LabelStyle.FILL,
      fillColor: Cesium.Color.WHITE,
      pixelOffset: new Cesium.Cartesian2(0, -60), //偏移量
      showBackground: true,
      backgroundColor: new Cesium.Color(0.5, 0.6, 1, 1.0),
      // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
    },
    // polyline: {
    //   positions: [
    //     Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 80),
    //     Cesium.Cartesian3.fromDegrees(pos[0], pos[1], 100),
    //   ],
    //   width: new Cesium.ConstantProperty(5),
    //   // material : Cesium.Color.fromRandom({alpha : 1.0}),
    //   material: new Cesium.PolylineGlowMaterialProperty({
    //     glowPower: 3,
    //     color: Cesium.Color.fromRandom({ alpha: 1.0 }),
    //   }),
    //   // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 100000, 0.0)
    // },
    billboard: {
      //图标
      image: imgaes,
      width: 25,
      // pixelOffset: new Cesium.Cartesian2(0, -50), //偏移量
      pixelOffset: new Cesium.Cartesian2(0, -25), //偏移量
      height: 50,
      // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
    },
  })

  return entity
}

const getViewerReady = function () {
  return new Promise((resolve) => {
    if (!window.viewer) {
      setTimeout(() => {
        resolve(this.getViewerReady())
      }, 30)
    } else {
      resolve(this)
    }
  })
}

export { loadPoint, loadPointIcon, getViewerReady, loadGeojson,getFinalPos, loadShp,drawAndShareImage }
